from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import memcache, datastore_errors 

from marketdata.models import MarketStats
from marketdata.statistic import TradeHubs
from xml.dom.minidom import Document

from datetime import  datetime

import logging

_keys = ['minimum', 'maximum', 'median', 'average']
_stat = {'minimum': "0", 'maximum' : "0", 'median' : "0", 'average' : "0",'orders' : "0",'movement' : "0"}
_ckeys = ['orders','movement','updated']
_cstat = {'orders': "0",'movement': "0",'updated': "0"}


def _sumtostr(_sum):
    return "%d.%02d" % (_sum/100, _sum % 100)


class ApiHandler(webapp.RequestHandler):
    def get(self):
        parameters = self.request.arguments()                           # The parameters from the submitted by the user
        self.response.headers['Content-Type'] = 'application/xml;charset=UTF-8' # Set the output MIME type to XML
        doc = Document()
        api = doc.createElement("eve-advisor")
        api.setAttribute("api-version","1.0")
        doc.appendChild(api)
        items = self.request.get_all("item")
        if len(items) :
            systems = self.request.get_all("system")
            if len(systems) == 0:
                systems=[30000142]
            for item in items:
                _type = doc.createElement("type")
                _type.setAttribute("id",item)
                api.appendChild(_type)
                for system in systems:
                    _system = doc.createElement("system")
                    _system.setAttribute("id",system)
                    _type.appendChild(_system)
                    _key="%06d%09d" % (long(item),long(system))
                    _buystat=memcache.get_multi(_stat.keys(),key_prefix=_key+"_buy")
                    _sellstat=memcache.get_multi(_stat.keys(),key_prefix=_key+"_sell")
                    _comonstat=memcache.get_multi(_cstat.keys(),key_prefix=_key+"_common")
                    if len(_buystat) != 4 or len(_sellstat) != 4 or len(_commonstat) != 3:
                        marketstat = MarketStats.get_by_key_name(_key)
                        _buystat = _stat.copy()
                        _sellstat = _stat.copy()
                        _commonstat = _cstat.copy()
                        if marketstat:
                            _buystat['minimum'] = _sumtostr(marketstat.minBuyPrice)
                            _buystat['maximum'] = _sumtostr(marketstat.maxBuyPrice)
                            _buystat['median'] = _sumtostr(marketstat.medianBuyPrice)
                            _buystat['average'] = _sumtostr(marketstat.averageBuyPrice)
                            _sellstat['minimum'] = _sumtostr(marketstat.minSellPrice)
                            _sellstat['maximum'] = _sumtostr(marketstat.maxSellPrice)
                            _sellstat['median'] = _sumtostr(marketstat.medianSellPrice)
                            _sellstat['average'] = _sumtostr(marketstat.averageSellPrice)
                            _commonstat['orders'] = str(marketstat.ordersBuy + marketstat.ordersSell)
                            _commonstat['movement'] = str(marketstat.volBuyEntered + marketstat.volSellEntered - marketstat.volBuyRemaining - marketstat.volSellRemaining)
                            _commonstat['updated'] = marketstat.updated.date().isoformat()
                            memcache.set_multi(_buystat,time=3600,key_prefix=_key+"_buy")
                            memcache.set_multi(_sellstat,time=3600,key_prefix=_key+"_sell")
                            memcache.set_multi(_commonstat,time=3600,key_prefix=_key+"_common")
                    _buy = doc.createElement("buy")
                    _system.appendChild(_buy)
                    for s_key in _keys:
                        _itemstat = doc.createElement(s_key)
                        _value = doc.createTextNode(_buystat[s_key])
                        _itemstat.appendChild(_value)
                        _buy.appendChild(_itemstat)
                    _sell = doc.createElement("sell")
                    _system.appendChild(_sell)
                    for s_key in _keys:
                        _itemstat = doc.createElement(s_key)
                        _value = doc.createTextNode(_sellstat[s_key])
                        _itemstat.appendChild(_value)
                        _sell.appendChild(_itemstat)
                    _common = doc.createElement("common")
                    _system.appendChild(_common)
                    for s_key in _ckeys:
                        _itemstat = doc.createElement(s_key)
                        _value = doc.createTextNode(_commonstat[s_key])
                        _itemstat.appendChild(_value)
                        _common.appendChild(_itemstat)
                    pass
                pass
            pass
        pass
        self.response.out.write(doc.toxml("utf-8"))

application = webapp.WSGIApplication([('/api/marketdata/item.xml', ApiHandler)], debug=True) 

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

